//
//  FreeNewProductViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/10/21.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "FreeNewProductCell.h"
#import "FreeNewHeaderView.h"
#import "TT_BaseNaviView.h"
#import "CommonCouponModel.h"


#import "ProductDetailViewController.h"
#import "FreeNewProductViewController.h"

@interface FreeNewProductViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableview;

@property (nonatomic, strong) NSMutableArray <CommonPackageModel *> *dataArray;

@property (nonatomic, strong) NSMutableArray <CommonCouponModel *> *couponArray;

@property (nonatomic, strong) FreeNewHeaderView *headerView;

@property (nonatomic, strong) TT_BaseNaviView *naviView;

@property (nonatomic, strong) UIButton *shareBtn;

@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation FreeNewProductViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self refreshParam];
    [self request_goodsList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessAction) name:@"BA_LoginSuccess" object:nil];
}

- (void)refreshParam {
    self.pageSize = 20;
    self.pageNum = 1;
}

- (void)loginSuccessAction {
    [self.tableview reloadData];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

- (void)initView {

    //屏幕常亮
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
    
    if([self.tableview respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        if (@available(iOS 11.0, *)) {
            self.tableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
    }
    
    [self.view addSubview:self.tableview];
    
    self.naviView = [[NSBundle mainBundle] loadNibNamed:@"TT_BaseNaviView"owner:nil options:nil].firstObject;
    self.naviView.titleLab.text = @"";
    [self.naviView.backBtn setImage:[UIImage imageNamed:@"public_back_white"] forState:UIControlStateNormal];
    [self.view addSubview:self.naviView];
    [self.naviView addSubview:self.shareBtn];
    
    [self.naviView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(kStatusBarHeight + NavBar_Height);
    }];
    
    [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.bottom.mas_equalTo(0);
        make.width.height.mas_equalTo(44);
    }];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
        
    self.headerView =  [[NSBundle mainBundle] loadNibNamed:@"FreeNewHeaderView"owner:nil options:nil].firstObject;
    self.headerView.frame = CGRectMake(0, 0, TTScreenWidth, TTScreenWidth/1.07);

    self.tableview.tableHeaderView = self.headerView;
    self.headerView.autoresizingMask = UIViewAutoresizingNone;
        
    [self initViewAction];
    
    [self.tableview reloadData];

}



- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)think {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)cache {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initViewAction {
    
    [self.naviView.backBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];

    WEAKSELF
    self.headerView.FreeNewHeaderViewBlock = ^{
      
        if (weakSelf.couponArray.count > 0) {
            [weakSelf request_getCouponWith:weakSelf.couponArray.firstObject.scoId];
        } else {
            [SVProgressHUD showErrorWithStatus:@"当前优惠券已领完"];
            [SVProgressHUD dismissWithDelay:1];
        }
        
    };
}

#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return TTScreenWidth/3;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
    vc.goodsId = self.dataArray[indexPath.row].goodsId;
    [self.navigationController pushViewController:vc animated:YES];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    FreeNewProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FreeNewProductCellID"];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    [cell fillCellWithModel:self.dataArray[indexPath.row]];
    
    return cell;
}

- (UIButton *)shareBtn {
    if (!_shareBtn) {
        _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_shareBtn setImage:[UIImage imageNamed:@"store_fenxiang_w"] forState:UIControlStateNormal];
        [_shareBtn addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    }
    return _shareBtn;
}

#pragma mark Share
- (void)share {
    
    CommonShareModel *model = [[CommonShareModel alloc] init];
    model.url = [NSString stringWithFormat:@"%@/activity/xinrenzx.html?myCode=%@", BA_Global_Domain,[TTUserModel sharedObject].myCode];
    model.title = @"新用户首单0元";
    model.content = @"新人豪礼0元购、百亿补贴等你来！平台婚礼管家为您提供更放心更优质的的1对1婚礼服务。";
    model.image = B_FREENEW_SHARE_IMG;
    [[TT_ShareManager share] callShareViewWithModel:model];
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xF54741);

        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"FreeNewProductCell" bundle:nil] forCellReuseIdentifier:@"FreeNewProductCellID"];
        
        WEAKSELF
//        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
//            [weakSelf refreshParam];
//            [weakSelf request_goodsList];
//        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_goodsList];
        }];
        
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;

    }
    return _tableview;
}

- (void)request_goodsList {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    NSMutableDictionary *t = @{}.mutableCopy;
    [dic setValue:t forKey:@"t"];
    [t setValue:@"2" forKey:@"goodsMold"];
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];

    if (self.shouldStatisticsl) {
        [t setValue:@"1" forKey:@"isStatistics"];
        
    }

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_NewFreeProductList];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *sellerGoodsList = [resultDic valueForKey:@"sellerGoodsList"];
                NSArray *sysCouponList = [resultDic valueForKey:@"sysCouponList"];

                if (weakSelf.pageNum == 1) {
                    weakSelf.couponArray = @[].mutableCopy;
                    weakSelf.dataArray = @[].mutableCopy;

                }
                
                if ([sysCouponList isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < sysCouponList.count; i++) {
                        NSDictionary *listDic = sysCouponList[i];
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            CommonCouponModel *model = [CommonCouponModel modelWithDictionary:sysCouponList[i]];
                            [weakSelf.couponArray addObject:model];
                        }
                    }
                }
                                
                if ([sellerGoodsList isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < sellerGoodsList.count; i++) {
                        NSDictionary *listDic = sellerGoodsList[i];
                        if ([listDic isKindOfClass:[NSDictionary class]]) {
                            CommonPackageModel *model = [CommonPackageModel modelWithJSON:sellerGoodsList[i]];

                            [weakSelf.dataArray addObject:model];
                        }
                    }
                }
                
                [weakSelf initView];
                
                if (weakSelf.couponArray.count > 0) {
                    weakSelf.headerView.usableDateLab.text = [NSString stringWithFormat:@"使用时间：领取后%@天内可用",weakSelf.couponArray.firstObject.effectiveDays];
                } else {
                    weakSelf.headerView.usableDateLab.text = @"";
                }

            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
    
}

- (void)request_getCouponWith:(NSString *)scoId {
    
    WEAKSELF
    [[BA_BusinessHelper shared] callgetCouponWith:scoId And:@"" comption:^(BOOL success) {

        if (success) {
            [SVProgressHUD showSuccessWithStatus:@"领取成功"];
            [SVProgressHUD dismissWithDelay:1];
            weakSelf.headerView.couponGetBtn.userInteractionEnabled = NO;
            [weakSelf.headerView.couponGetBtn setImage:[UIImage imageNamed:@"freeNew_sel"] forState:UIControlStateNormal];
        }

    }];
}

@end
